<!--
 * @Description:锚点组件
 * @Author: wyh19
 * @Date: 2021-05-22
-->
<template>
  <div ref="anchor" class="anchor">
    <div class="anchor-track"></div>
    <div class="anchor-list">
      <div v-for="node in sections" :key="node.label" :label="node.index" :data-anchor="node.label"
           :class="[node.ismain?'anchor-main-node':'anchor-sub-node',{'anchor-node-active':currentSection===node.label}]"
           @click="handleClick(node.label)">
        {{ node.label }}
        <span v-if="node.tip" class="highlight-tag">!</span>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash.debounce'
export default {
  props: {
    pageBlock: HTMLElement
  },
  data() {
    return {
      currentSection: '',
      sections: []
    }
  },
  watch: {
    currentSection() {
      this.showCurrentSectionsAnchor()
    }
  },
  mounted() {
    this.sections = this.getSectionsData(this.pageBlock)
    // 初始化时高亮第一个
    this.currentSection = this.getCurrentSection()
    this.debouncedPageScrollHandler = debounce(this.handlePageScroll, 100)
    this.pageBlock.addEventListener('scroll', this.debouncedPageScrollHandler)
  },
  beforeDestroy() {
    this.pageBlock.removeEventListener('scroll', this.debouncedPageScrollHandler)
  },
  methods: {
    reRender() {
      this.sections = this.getSectionsData(this.pageBlock)
      this.currentSection = this.getCurrentSection()
    },
    // 从pageBlock中获取章节信息
    getSectionsData(pageBlock) {
      let mainIndex = 0 // 主节点的数字序号
      let subIndex = 0 // 子节点的数字序号
      // 查询出data-section的节点，并转化成数组
      const sections = Array.from(pageBlock.querySelectorAll('[data-section]'))
      // map转化节点数组为最终的数据
      return sections.map((item, index) => {
        let ismain = false
        if ('ismain' in item.dataset) {
          ismain = true
          mainIndex++
          // 遇到新的主节点，重置subIndex
          subIndex = 0
        } else {
          subIndex++
        }
        return {
          // 如果有data-tip属性，则为true，反之为false
          tip: 'tip' in item.dataset,
          ismain,
          index: ismain ? mainIndex : `${mainIndex}.${subIndex}`,
          label: item.dataset.section,
          top: item.offsetTop
        }
      })
    },
    // 页面的滚动事件处理函数
    handlePageScroll(e) {
      e.stopPropagation()
      this.currentSection = this.getCurrentSection()
    },
    // 计算出当前滚动到的章节
    getCurrentSection() {
      // 当前表单的的scrollTop
      const currentScrollTop = this.pageBlock.scrollTop
      const sections = this.sections
      const length = sections.length
      let currentSection
      // 依次和各节点原先的offsetTop进行比较
      for (let i = 0; i < length; i++) {
        // 如果scrollTop正好和某节点的offsetTop相等
        // 或者scrollTop介于当前判断的节点和下一个节点之间
        // 由于需要下一个节点，所以当前节点不能是最后一个节点
        if (currentScrollTop === sections[i].top ||
          (i < length - 1 &&
            currentScrollTop > sections[i].top &&
            currentScrollTop < sections[i + 1].top)) {
          currentSection = sections[i].label
          break
        } else if (i === length - 1) {
          // 如果判断到一个节点，只要 scrollTop大于节点的offsetTop即可
          if (currentScrollTop > sections[i].top) {
            currentSection = sections[i].label
            break
          }
        }
      }
      return currentSection
    },
    handleClick(label) {
      // 设置当前锚点对应章节
      this.currentSection = label
      // 查找到到该章节的dom
      const section = this.pageBlock.querySelector(`[data-section=${label}]`)
      // 延迟执行
      setTimeout(() => {
        // 平滑滚动至该章节
        section.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        })
      })
    },
    showCurrentSectionsAnchor() {
      // 给锚点增加data-anchor属性，便于查找
      const anchor = this.$refs['anchor'].querySelector(`[data-anchor=${this.currentSection}]`)
      if (anchor) {
        const wrapper = anchor.parentElement
        const clientHeight = wrapper.clientHeight
        const offsetTop = anchor.offsetTop
        // 计算当前元素是否处于容器可视区域中间偏下的位置，如果是的，则让容器滚动使得元素可视居中
        if (offsetTop > clientHeight / 2) {
          wrapper.scrollTop = offsetTop - clientHeight / 2
        } else {
          wrapper.scrollTop = 0
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.anchor {
  position: relative;
  width: 100%;
  height: 100%;
}
.anchor-track {
  position: absolute;
  left: 4px;
  top: -10px;
  bottom: -10px;
  width: 1px;
  background: #aaa;
  // 上下的空心圆圈
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -4px;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    border: 1px solid #ccc;
    background: #fff;
  }
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: -4px;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    border: 1px solid #ccc;
    background: #fff;
  }
}
.anchor-list {
  position: relative;
  padding: 12px;
  width: 100%;
  height: 100%;
  // 宽高尽量依赖外界容器
  // 如果容器未处理，则使用默认最小值
  min-width: 120px;
  min-height: 120px;
  overflow-x: visible;
  overflow-y: auto;
  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
  }
}

.anchor-main-node {
  position: relative;
  margin: 8px 0;
  font-size: 14px;
  font-weight: bold;
  color: #555;
  cursor: pointer;
  &::before {
    content: attr(label);
    margin-left: 6px;
    margin-right: 6px;
  }
  // 新增实心点
  &::after {
    content: '';
    position: absolute;
    left: -11px;
    top: 3px;
    width: 8px;
    height: 8px;
    border-radius: 8px;
    background: #666;
  }
}
.anchor-sub-node {
  position: relative;
  margin: 8px 0;
  padding-left: 22px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  &::before {
    content: attr(label);
    margin-right: 4px;
  }
}
.anchor-node-active {
  color: #38f;
  // 新增三角
  &::after {
    content: '';
    position: absolute;
    left: -8px;
    top: 0px;
    width: 0px;
    height: 0px;
    border: 8px solid transparent;
    border-left-color: #38f;
    background: transparent;
    border-radius: 0;
  }
}
.highlight-tag {
  display: inline-block;
  text-align: center;
  margin-left: 8px;
  width: 16px;
  height: 16px;
  border-radius: 16px;
  background: crimson;
  color: #efefef;
}
</style>
